<%@ page import="java.io.*" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>


<%

    //File file = new File(request.getServletContext().getRealPath("/") + path);//构造要下载的文件

    String fileName = "中文.gif";
    String filePath = request.getServletContext().getRealPath("/") + "affix/" + fileName;

    downloadFile(request, response, filePath, fileName);
%>

<%!
    /**
     * 下载文件
     *
     * @param request
     *            HttpServletRequest
     * @param response
     *            HttpServletResponse
     * @param filePath
     *            文件全路径 eg : D:/work/IdeaProjects/JavaWebTest/xxx/xxx.doc
     * @param fileName
     *            指定客户端下载时显示的文件名 eg : xxx.doc
     * @throws IOException
     */
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response, String filePath, String fileName)
            throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        bis = new BufferedInputStream(new FileInputStream(filePath));
        bos = new BufferedOutputStream(response.getOutputStream());

        long fileLength = new File(filePath).length();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
		/*
		 * 解决各浏览器的中文乱码问题
		 */
        String userAgent = request.getHeader("User-Agent");
        byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
        fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));

        response.setHeader("Content-Length", String.valueOf(fileLength));
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();

    }
%>

</body>
</html>
